﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using System.Net;

namespace wojilu
{
    /// <summary>
    /// Thumbnail 的摘要说明。
    /// </summary>
    public class Thumbnail
    {
        private Image srcImage;
        private string srcFileName;

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="FileName">原始图片路径</param>
        public bool SetImage(string FileName)
        {
            srcFileName = PathHelper.Map(FileName);
            try
            {
                srcImage = Image.FromFile(srcFileName);
            }
            catch
            {
                return false;
            }
            return true;

        }

        /// <summary>
        /// 回调
        /// </summary>
        /// <returns></returns>
        public bool ThumbnailCallback()
        {
            return false;
        }

        /// <summary>
        /// 生成缩略图,返回缩略图的Image对象
        /// </summary>
        /// <param name="Width">缩略图宽度</param>
        /// <param name="Height">缩略图高度</param>
        /// <returns>缩略图的Image对象</returns>
        public Image GetImage(int Width, int Height)
        {
            Image img;
            Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
            img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
            return img;
        }

        /// <summary>
        /// 保存缩略图
        /// </summary>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        public void SaveThumbnailImage(int Width, int Height)
        {
            switch (Path.GetExtension(srcFileName).ToLower())
            {
                case ".png":
                    SaveImage(Width, Height, ImageFormat.Png);
                    break;
                case ".gif":
                    SaveImage(Width, Height, ImageFormat.Gif);
                    break;
                default:
                    SaveImage(Width, Height, ImageFormat.Jpeg);
                    break;
            }
        }

        /// <summary>
        /// 生成缩略图并保存
        /// </summary>
        /// <param name="Width">缩略图的宽度</param>
        /// <param name="Height">缩略图的高度</param>
        /// <param name="imgformat">保存的图像格式</param>
        /// <returns>缩略图的Image对象</returns>
        public void SaveImage(int Width, int Height, ImageFormat imgformat)
        {
            if (imgformat != ImageFormat.Gif && (srcImage.Width > Width) || (srcImage.Height > Height))
            {
                Image img;
                Image.GetThumbnailImageAbort callb = new Image.GetThumbnailImageAbort(ThumbnailCallback);
                img = srcImage.GetThumbnailImage(Width, Height, callb, IntPtr.Zero);
                srcImage.Dispose();
                img.Save(srcFileName, imgformat);
                img.Dispose();
            }
        }

        #region Helper

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image">Image 对象</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="ici">指定格式的编解码参数</param>
        private static void SaveImage(Image image, string savePath, ImageCodecInfo ici)
        {
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(Encoder.Quality, ((long)100));
            image.Save(savePath, ici, parameters);
            parameters.Dispose();
        }

        /// <summary>
        /// 获取图像编码解码器的所有相关信息
        /// </summary>
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
        /// <returns>返回图像编码解码器的所有相关信息</returns>
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType)
                    return ici;
            }
            return null;
        }

        /// <summary>
        /// 计算新尺寸
        /// </summary>
        /// <param name="width">原始宽度</param>
        /// <param name="height">原始高度</param>
        /// <param name="maxWidth">最大新宽度</param>
        /// <param name="maxHeight">最大新高度</param>
        /// <returns></returns>
        private static Size ResizeImage(int width, int height, int maxWidth, int maxHeight)
        {
            decimal MAX_WIDTH = (decimal)maxWidth;
            decimal MAX_HEIGHT = (decimal)maxHeight;
            decimal ASPECT_RATIO = MAX_WIDTH / MAX_HEIGHT;

            int newWidth, newHeight;
            decimal originalWidth = (decimal)width;
            decimal originalHeight = (decimal)height;

            if (originalWidth > MAX_WIDTH || originalHeight > MAX_HEIGHT)
            {
                decimal factor;
                // determine the largest factor 
                if (originalWidth / originalHeight > ASPECT_RATIO)
                {
                    factor = originalWidth / MAX_WIDTH;
                    newWidth = Convert.ToInt32(originalWidth / factor);
                    newHeight = Convert.ToInt32(originalHeight / factor);
                }
                else
                {
                    factor = originalHeight / MAX_HEIGHT;
                    newWidth = Convert.ToInt32(originalWidth / factor);
                    newHeight = Convert.ToInt32(originalHeight / factor);
                }
            }
            else
            {
                newWidth = width;
                newHeight = height;
            }
            return new Size(newWidth, newHeight);
        }

        /// <summary>
        /// 得到图片格式
        /// </summary>
        /// <param name="name">文件名称</param>
        /// <returns></returns>
        public static ImageFormat GetFormat(string name)
        {
            string ext = name.Substring(name.LastIndexOf(".") + 1);
            switch (ext.ToLower())
            {
                case "jpg":
                case "jpeg":
                    return ImageFormat.Jpeg;
                case "bmp":
                    return ImageFormat.Bmp;
                case "png":
                    return ImageFormat.Png;
                case "gif":
                    return ImageFormat.Gif;
                default:
                    return ImageFormat.Jpeg;
            }
        }
        #endregion

        /// <summary>
        /// 制作小正方形
        /// </summary>
        /// <param name="image">图片对象</param>
        /// <param name="newFileName">新地址</param>
        /// <param name="newSize">长度或宽度</param>
        public static void MakeSquareImage(Image image, string newFileName, int newSize)
        {
            int i = 0;
            int width = image.Width;
            int height = image.Height;
            if (width > height)
                i = height;
            else
                i = width;

            Bitmap b = new Bitmap(newSize, newSize);

            try
            {
                Graphics g = Graphics.FromImage(b);
                g.InterpolationMode = InterpolationMode.High;
                g.SmoothingMode = SmoothingMode.HighQuality;

                //清除整个绘图面并以透明背景色填充
                g.Clear(Color.Transparent);
                if (width < height)
                    g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle(0, (height - width) / 2, width, width), GraphicsUnit.Pixel);
                else
                    g.DrawImage(image, new Rectangle(0, 0, newSize, newSize), new Rectangle((width - height) / 2, 0, height, height), GraphicsUnit.Pixel);

                SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower()));
            }
            finally
            {
                image.Dispose();
                b.Dispose();
            }
        }

        /// <summary>
        /// 制作小正方形
        /// </summary>
        /// <param name="fileName">图片文件名</param>
        /// <param name="newFileName">新地址</param>
        /// <param name="newSize">长度或宽度</param>
        public static void MakeSquareImage(string fileName, string newFileName, int newSize)
        {
            MakeSquareImage(Image.FromFile(fileName), newFileName, newSize);
        }

        /// <summary>
        /// 对图片进行居中填充操作
        /// </summary>
        /// <param name="SourceFileName">源图片</param>
        /// <param name="Width">宽度</param>
        /// <param name="Height">高度</param>
        /// <param name="BorderColor">边框颜色</param>
        /// <param name="BackColor">颜色名称</param>
        /// <param name="Position">位置</param>
        /// <param name="DestinationFileName">目标图片</param>
        public static void MakeSquareImage(string SourceFileName, int Width, int Height, string BorderColor, string BackColor, PositionMode Position, string DestinationFileName)
        {
            byte[] bytes = MakeSquareImage(File.ReadAllBytes(SourceFileName), Width, Height, BorderColor, BackColor, Position);
            File.WriteAllBytes(DestinationFileName, bytes);
        }

        /// <summary>
        /// 对图片进行居中填充操作
        /// </summary>
        /// <param name="ImageBytes">源图数据</param>
        /// <param name="Width">宽度</param>
        /// <param name="Height">高度</param>
        /// <param name="BorderColor">边框颜色</param>
        /// <param name="BackColor">颜色名称</param>
        /// <param name="Position">位置</param>
        /// <returns>目标图数据</returns>
        public static byte[] MakeSquareImage(byte[] ImageBytes, int Width, int Height, string BorderColor, string BackColor, PositionMode Position)
        {
            Image image = Image.FromStream(new MemoryStream(ImageBytes), false, false);
            var horizontalResolution = image.HorizontalResolution;//获取上传文件的水平分辨率（以“像素/英寸”为单位）。 
            var verticalResolution = image.VerticalResolution;//获取上传文件的垂直分辨率（以“像素/英寸”为单位）。 
            Bitmap bitmap = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
            bitmap.SetResolution(horizontalResolution, verticalResolution); //设置分辨率
            Graphics graphics = Graphics.FromImage(bitmap);
            Rectangle source = new Rectangle(0, 0, image.Width, image.Height);

            Rectangle destRect = GetCenterRect(source, Position, Width, Height);
            MemoryStream stream = new MemoryStream();
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.SmoothingMode = SmoothingMode.AntiAlias;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            graphics.FillRectangle(new SolidBrush(GetColor(BackColor)), 0, 0, bitmap.Width, bitmap.Height);
            graphics.DrawImage(image, destRect, source, GraphicsUnit.Pixel);
            graphics.DrawRectangle(new Pen(new SolidBrush(GetColor(BorderColor))), 0, 0, bitmap.Width, bitmap.Height);
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            ImageCodecInfo encoderInfo = GetEncoderInfo("image/jpeg");
            if (encoderInfo != null)
            {
                bitmap.Save(stream, encoderInfo, encoderParams);
            }
            else
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
            }
            encoderParams.Dispose();
            encoderParams = null;
            graphics.Dispose();
            graphics = null;
            bitmap.Dispose();
            bitmap = null;
            image.Dispose();
            image = null;
            return stream.GetBuffer();
        }

        /// <summary>
        /// 填充目标位置
        /// </summary>
        /// <param name="Source">源图尺寸</param>
        /// <param name="Position">目标位置</param>
        /// <param name="Width">宽度</param>
        /// <param name="Height">高度</param>
        /// <returns>缩放后的尺寸</returns>
        private static Rectangle GetCenterRect(Rectangle Source, PositionMode Position, int Width, int Height)
        {
            int num;
            int num2;
            int width;
            int height;
            if ((Source.Width > Width) || (Source.Height > Height))
            {
                double num5 = ((double)Width) / ((double)Source.Width);
                double num6 = ((double)Height) / ((double)Source.Height);
                if (num5 > num6)
                {
                    width = (int)Math.Floor((double)(num6 * Source.Width));
                    height = Height;
                }
                else
                {
                    width = Width;
                    height = (int)Math.Floor((double)(num5 * Source.Height));
                }
            }
            else
            {
                width = Source.Width;
                height = Source.Height;
            }
            switch (Position)
            {
                case PositionMode.TopLeft:
                    num = 0;
                    num2 = 0;
                    break;

                case PositionMode.TopRight:
                    num = (int)Math.Floor((double)((Width - width) / 2.0));
                    num2 = 0;
                    break;

                case PositionMode.BottomLeft:
                    num = (int)Math.Floor((double)((Width - width) / 2.0));
                    num2 = Height - height;
                    break;

                case PositionMode.BottomRight:
                    num = Width - height;
                    num2 = (int)Math.Floor((double)((Height - height) / 2.0));
                    break;

                default:
                    num = (int)Math.Floor((double)((Width - width) / 2.0));
                    num2 = (int)Math.Floor((double)((Height - height) / 2.0));
                    break;
            }
            return new Rectangle(num, num2, width, height);
        }

        /// <summary>
        /// 制作远程小正方形
        /// </summary>
        /// <param name="url">图片url</param>
        /// <param name="newFileName">新地址</param>
        /// <param name="newSize">长度或宽度</param>
        public static void MakeRemoteSquareImage(string url, string newFileName, int newSize)
        {
            Stream stream = GetRemoteImage(url);
            if (stream == null)
                return;
            Image original = Image.FromStream(stream);
            stream.Close();
            MakeSquareImage(original, newFileName, newSize);
        }

        /// <summary>
        /// 制作缩略图
        /// </summary>
        /// <param name="original">图片对象</param>
        /// <param name="newFileName">新图路径</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        public static void MakeThumbnailImage(Image original, string newFileName, int maxWidth, int maxHeight)
        {
            Size _newSize = ResizeImage(original.Width, original.Height, maxWidth, maxHeight);
            Image displayImage = new Bitmap(original, _newSize);

            try
            {
                displayImage.Save(newFileName, original.RawFormat);
            }
            finally
            {
                original.Dispose();
            }
        }

        /// <summary>
        /// 制作缩略图
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="newFileName">新图路径</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        public static void MakeThumbnailImage(string fileName, string newFileName, int maxWidth, int maxHeight)
        {
            MakeThumbnailImage(Image.FromFile(fileName), newFileName, maxWidth, maxHeight);
        }

        /// <summary>
        /// 制作远程缩略图
        /// </summary>
        /// <param name="url">图片URL</param>
        /// <param name="newFileName">新图路径</param>
        /// <param name="maxWidth">最大宽度</param>
        /// <param name="maxHeight">最大高度</param>
        public static void MakeRemoteThumbnailImage(string url, string newFileName, int maxWidth, int maxHeight)
        {
            Stream stream = GetRemoteImage(url);
            if (stream == null)
                return;
            Image original = Image.FromStream(stream);
            stream.Close();
            MakeThumbnailImage(original, newFileName, maxWidth, maxHeight);
        }

        /// <summary>
        /// 获取图片流
        /// </summary>
        /// <param name="url">图片URL</param>
        /// <returns></returns>
        private static Stream GetRemoteImage(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            request.ContentLength = 0;
            request.Timeout = 20000;
            HttpWebResponse response = null;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                return response.GetResponseStream();
            }
            catch
            {
                return null;
            }
        }

        /// <summary>
        /// 添加文字水印
        /// </summary>
        /// <param name="ImageBytes">源图数据</param>
        /// <param name="WatermarkText">水印文本</param>
        /// <param name="FontName">字体名称</param>
        /// <param name="FontSize">字体大小</param>
        /// <param name="ForeColor">字体前景色</param>
        /// <param name="Alpha">透明度 [0~100]</param>
        /// <param name="watermarkStatus">位置</param>
        /// <returns>目标图数据</returns>
        public static byte[] TextWatermark(byte[] ImageBytes, string WatermarkText, string FontName, int FontSize, string ForeColor, int Alpha, int watermarkStatus)
        {
            Image image = Image.FromStream(new MemoryStream(ImageBytes), false, false);
            Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
            Graphics graphics = Graphics.FromImage(bitmap);
            MemoryStream stream = new MemoryStream();
            Font font = new Font(FontName, (float)FontSize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF ef = graphics.MeasureString(WatermarkText, font);
            float num3 = 0f;
            float num4 = 0f;
            switch (watermarkStatus)
            {
                case 1:
                    num3 = (float)image.Width * (float).01;
                    num4 = (float)image.Height * (float).01;
                    break;
                case 2:
                    num3 = ((float)image.Width * (float).50) - (ef.Width / 2);
                    num4 = (float)image.Height * (float).01;
                    break;
                case 3:
                    num3 = ((float)image.Width * (float).99) - ef.Width;
                    num4 = (float)image.Height * (float).01;
                    break;
                case 4:
                    num3 = (float)image.Width * (float).01;
                    num4 = ((float)image.Height * (float).50) - (ef.Height / 2);
                    break;
                case 5:
                    num3 = ((float)image.Width * (float).50) - (ef.Width / 2);
                    num4 = ((float)image.Height * (float).50) - (ef.Height / 2);
                    break;
                case 6:
                    num3 = ((float)image.Width * (float).99) - ef.Width;
                    num4 = ((float)image.Height * (float).50) - (ef.Height / 2);
                    break;
                case 7:
                    num3 = (float)image.Width * (float).01;
                    num4 = ((float)image.Height * (float).99) - ef.Height;
                    break;
                case 8:
                    num3 = ((float)image.Width * (float).50) - (ef.Width / 2);
                    num4 = ((float)image.Height * (float).99) - ef.Height;
                    break;
                case 9:
                    num3 = ((float)image.Width * (float).99) - ef.Width;
                    num4 = ((float)image.Height * (float).99) - ef.Height;
                    break;
            }
            graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            graphics.DrawImage(image, 0, 0, image.Width, image.Height);
            graphics.DrawString(WatermarkText, font, new SolidBrush(Color.FromArgb(GetAlpha(Alpha), GetColor(ForeColor))), num3, num4);
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            ImageCodecInfo encoderInfo = GetEncoderInfo("image/jpeg");
            if (encoderInfo != null)
            {
                bitmap.Save(stream, encoderInfo, encoderParams);
            }
            else
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
            }
            encoderParams.Dispose();
            encoderParams = null;
            graphics.Dispose();
            graphics = null;
            bitmap.Dispose();
            bitmap = null;
            image.Dispose();
            image = null;
            return stream.GetBuffer();
        }

        /// <summary>
        /// 添加文字水印
        /// </summary>
        /// <param name="SourceFileName">源图片</param>
        /// <param name="WatermarkText">水印文本</param>
        /// <param name="FontName">字体名称</param>
        /// <param name="FontSize">字体大小</param>
        /// <param name="ForeColor">字体前景色</param>
        /// <param name="Alpha">透明度 [0~100]</param>
        /// <param name="watermarkStatus">位置</param>
        /// <param name="DestinationFileName">目标图片</param>
        public static void TextWatermark(string SourceFileName, string WatermarkText, string FontName, int FontSize, string ForeColor, int Alpha, int watermarkStatus, string DestinationFileName)
        {
            byte[] bytes = TextWatermark(File.ReadAllBytes(SourceFileName), WatermarkText, FontName, FontSize, ForeColor, Alpha, watermarkStatus);
            File.WriteAllBytes(DestinationFileName, bytes);
        }

        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="ImageBytes">源图数据</param>
        /// <param name="WatermarkBytes"></param>
        /// <param name="Alpha">透明度 [0~100]</param>
        /// <param name="Position">位置</param>
        /// <returns></returns>
        public static byte[] ImageWatermark(byte[] ImageBytes, byte[] WatermarkBytes, int Alpha, int watermarkStatus)
        {
            Image image = Image.FromStream(new MemoryStream(ImageBytes), false, false);
            Image image2 = Image.FromStream(new MemoryStream(WatermarkBytes), false, false);
            Bitmap bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
            Graphics graphics = Graphics.FromImage(bitmap);
            MemoryStream stream = new MemoryStream();
            float num = 0f;
            float num2 = 0f;
            switch (watermarkStatus)
            {
                case 1:
                    num = (int)(image.Width * (float).01);
                    num2 = (int)(image.Height * (float).01);
                    break;
                case 2:
                    num = (int)((image.Width * (float).50) - (image2.Width / 2));
                    num2 = (int)(image.Height * (float).01);
                    break;
                case 3:
                    num = (int)((image.Width * (float).99) - (image2.Width));
                    num2 = (int)(image.Height * (float).01);
                    break;
                case 4:
                    num = (int)(image.Width * (float).01);
                    num2 = (int)((image.Height * (float).50) - (image2.Height / 2));
                    break;
                case 5:
                    num = (int)((image.Width * (float).50) - (image2.Width / 2));
                    num2 = (int)((image.Height * (float).50) - (image2.Height / 2));
                    break;
                case 6:
                    num = (int)((image.Width * (float).99) - (image2.Width));
                    num2 = (int)((image.Height * (float).50) - (image2.Height / 2));
                    break;
                case 7:
                    num = (int)(image.Width * (float).01);
                    num2 = (int)((image.Height * (float).99) - image2.Height);
                    break;
                case 8:
                    num = (int)((image.Width * (float).50) - (image2.Width / 2));
                    num2 = (int)((image.Height * (float).99) - image2.Height);
                    break;
                case 9:
                    num = (int)((image.Width * (float).99) - (image2.Width));
                    num2 = (int)((image.Height * (float).99) - image2.Height);
                    break;
            }
            float num3 = ((Alpha >= 1) && (Alpha <= 100)) ? (((float)Alpha) / 100f) : 0.5f;
            float[][] numArray2 = new float[5][];
            float[] numArray3 = new float[5];
            numArray3[0] = 1f;
            numArray2[0] = numArray3;
            numArray3 = new float[5];
            numArray3[1] = 1f;
            numArray2[1] = numArray3;
            numArray3 = new float[5];
            numArray3[2] = 1f;
            numArray2[2] = numArray3;
            numArray3 = new float[5];
            numArray3[3] = num3;
            numArray2[3] = numArray3;
            numArray3 = new float[5];
            numArray3[4] = 1f;
            numArray2[4] = numArray3;
            float[][] newColorMatrix = numArray2;
            ColorMap map = new ColorMap
            {
                OldColor = Color.FromArgb(0xff, 0, 0xff, 0),
                NewColor = Color.FromArgb(0, 0, 0, 0)
            };
            ColorMap[] mapArray = new ColorMap[] { map };
            ColorMatrix matrix = new ColorMatrix(newColorMatrix);
            ImageAttributes imageAttr = new ImageAttributes();
            imageAttr.SetRemapTable(mapArray, ColorAdjustType.Bitmap);
            imageAttr.SetColorMatrix(matrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
            graphics.InterpolationMode = InterpolationMode.High;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.DrawImage(image, 0, 0, image.Width, image.Height);
            graphics.DrawImage(image2, new Rectangle((int)num, (int)num2, image2.Width, image2.Height), 0, 0, image2.Width, image2.Height, GraphicsUnit.Pixel, imageAttr);
            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
            ImageCodecInfo encoderInfo = GetEncoderInfo("image/jpeg");
            if (encoderInfo != null)
            {
                bitmap.Save(stream, encoderInfo, encoderParams);
            }
            else
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
            }
            encoderParams.Dispose();
            encoderParams = null;
            graphics.Dispose();
            graphics = null;
            bitmap.Dispose();
            bitmap = null;
            imageAttr.Dispose();
            imageAttr = null;
            image2.Dispose();
            image2 = null;
            image.Dispose();
            image = null;
            return stream.GetBuffer();
        }

        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="SourceFileName">源图片</param>
        /// <param name="WatermarkImage">水银图片</param>
        /// <param name="Alpha">透明度 [0~100]</param>
        /// <param name="Position">位置</param>
        /// <param name="DestinationFileName">目标图片</param>
        public static void ImageWatermark(string SourceFileName, string WatermarkImage, int Alpha, int watermarkStatus, string DestinationFileName)
        {
            byte[] watermarkBytes = File.ReadAllBytes(WatermarkImage);
            byte[] bytes = ImageWatermark(File.ReadAllBytes(SourceFileName), watermarkBytes, Alpha, watermarkStatus);
            File.WriteAllBytes(DestinationFileName, bytes);
        }

        // Nested Types
        /// <summary>
        /// 功能：位置模式
        /// </summary>
        public enum PositionMode
        {
            None,
            TopLeft,
            TopRight,
            Middle,
            BottomLeft,
            BottomRight
        }

        /// <summary>
        /// 功能：排列模式
        /// </summary>
        public enum RangeMode
        {
            Vertical,
            Horizontal
        }

        /// <summary>
        /// 功能：图片旋转模式
        /// </summary>
        public enum RotateMode
        {
            TurnLeft,
            TurnRight,
            TurnVertical,
            TurnHorizontal
        }

        /// <summary>
        /// 获取透明度
        /// </summary>
        /// <param name="Alpha">透明度</param>
        /// <returns>透明度</returns>
        private static int GetAlpha(int Alpha)
        {
            if ((Alpha >= 1) && (Alpha <= 100))
            {
                return (int)(Alpha * 2.55);
            }
            return 0x7d;
        }

        /// <summary>
        /// 根据颜色代码获取颜色
        /// </summary>
        /// <param name="ColorName">颜色代码</param>
        /// <returns>颜色</returns>
        private static Color GetColor(string ColorName)
        {
            if (ColorName.StartsWith("#"))
            {
                ColorConverter converter = new ColorConverter();
                return (Color)converter.ConvertFromString(ColorName);
            }
            return Color.FromName(ColorName);
        }

        /// <summary>
        /// 获取指定图片数据类型
        /// </summary>
        /// <param name="TargetMimeType">数据类型</param>
        /// <returns>返回图像参数</returns>
        private static ImageCodecInfo GetEncoderInfo(string TargetMimeType)
        {
            ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
            for (int i = 0; i < imageEncoders.Length; i++)
            {
                if (imageEncoders[i].MimeType == TargetMimeType)
                {
                    return imageEncoders[i];
                }
            }
            return null;
        }

        /// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="watermarkFilename">水印文件名</param>
        /// <param name="watermarkStatus">图片水印位置</param>
        /// <param name="watermarkTransparency">图片水印透明度 取值范围1--100 (100为不透明)</param>
        /// <param name="quality">是否是高质量图片 取值范围0--100</param>
        public static void AddImageSignPic(Image img, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency)
        {
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            Image watermark = new Bitmap(watermarkFilename);

            if (watermark.Height >= img.Height || watermark.Width >= img.Width)
                return;

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float transparency = 0.5F;
            if (watermarkTransparency >= 1 && watermarkTransparency <= 100)
                transparency = (watermarkTransparency / 100.0F);


            float[][] colorMatrixElements = {
												new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
												new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
												new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
												new float[] {0.0f,  0.0f,  0.0f,  transparency, 0.0f},
												new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
											};

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;

            switch (watermarkStatus)
            {
                case 1:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 2:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 3:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)(img.Height * (float).01);
                    break;
                case 4:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 5:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 6:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).50) - (watermark.Height / 2));
                    break;
                case 7:
                    xpos = (int)(img.Width * (float).01);
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 8:
                    xpos = (int)((img.Width * (float).50) - (watermark.Width / 2));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
                case 9:
                    xpos = (int)((img.Width * (float).99) - (watermark.Width));
                    ypos = (int)((img.Height * (float).99) - watermark.Height);
                    break;
            }

            g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                    ici = codec;
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
                quality = 80;

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
                img.Save(filename, ici, encoderParams);
            else
                img.Save(filename);

            g.Dispose();
            img.Dispose();
            watermark.Dispose();
            imageAttributes.Dispose();
        }


        /// <summary>
        /// 增加图片文字水印
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <param name="watermarkText">水印文字</param>
        /// <param name="watermarkStatus">图片水印位置</param>
        public static void AddImageSignText(Image img, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize)
        {
            Graphics g = Graphics.FromImage(img);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel);
            SizeF crSize;
            crSize = g.MeasureString(watermarkText, drawFont);

            float xpos = 0;
            float ypos = 0;

            switch (watermarkStatus)
            {
                case 1:
                    xpos = (float)img.Width * (float).01;
                    ypos = (float)img.Height * (float).01;
                    break;
                case 2:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = (float)img.Height * (float).01;
                    break;
                case 3:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = (float)img.Height * (float).01;
                    break;
                case 4:
                    xpos = (float)img.Width * (float).01;
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 5:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 6:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = ((float)img.Height * (float).50) - (crSize.Height / 2);
                    break;
                case 7:
                    xpos = (float)img.Width * (float).01;
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
                case 8:
                    xpos = ((float)img.Width * (float).50) - (crSize.Width / 2);
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
                case 9:
                    xpos = ((float)img.Width * (float).99) - crSize.Width;
                    ypos = ((float)img.Height * (float).99) - crSize.Height;
                    break;
            }

            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1);
            g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos);

            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo ici = null;
            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.MimeType.IndexOf("jpeg") > -1)
                    ici = codec;
            }
            EncoderParameters encoderParams = new EncoderParameters();
            long[] qualityParam = new long[1];
            if (quality < 0 || quality > 100)
                quality = 80;

            qualityParam[0] = quality;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam);
            encoderParams.Param[0] = encoderParam;

            if (ici != null)
                img.Save(filename, ici, encoderParams);
            else
                img.Save(filename);

            g.Dispose();
            img.Dispose();
        }

    }
}
